package com.gulimall.product.web;

import com.gulimall.product.entity.CategoryEntity;
import com.gulimall.product.service.CategoryService;
import com.gulimall.product.vo.Catelog2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Controller
public class IndexController {

    @Autowired
    CategoryService categoryService;

    @Autowired
    RedissonClient redissonClient;

    @GetMapping({"/", "/index.html"})
    public String indexPage(Model model) {

        System.out.println("" + Thread.currentThread().getId());
        List<CategoryEntity> entities = categoryService.getLevelNoeCategory();

        model.addAttribute("categorys", entities);

        return "index";
    }
    // index/catalog.json


    @ResponseBody
    @GetMapping("/index/catalog.json")
    public Map<String, List<Catelog2Vo>> getCatelogJson() {

        Map<String, List<Catelog2Vo>> map = categoryService.getCatalogJson();

        return map;
    }


    @GetMapping("hello")
    public String hello() {

        RLock lock = redissonClient.getLock("my-lock");

        lock.lock();

        //最佳实践
//        lock.lock(30, TimeUnit.SECONDS); 省掉整个续期操作
        try {
            System.out.println("加锁" + Thread.currentThread().getId());
            Thread.sleep(30000);
        } catch (Exception e) {

        } finally {
            System.out.println("解开锁" + Thread.currentThread().getId());
            lock.unlock();
        }

        return "hello";
    }
}
